﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Reflection;
using System.Xml;
using CubeDAL;
using SysInfo;
using CrossQuery;
using System.Windows.Forms.DataVisualization.Charting;
using System.Collections;

namespace CubePresentation
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        MySQLWrapper dataSqlWrapper;
        MySQLWrapper mappingSqlWrapper;

        //need to put in configuration file
        string sqlServer = Constant.DB_SERVER;
        string dataSqlDatabase = Constant.DB_DATABASE;
        string mappingSqlDatabase = Constant.DB_MAP_DATABASE;
        string sqlUser = Constant.DB_USER;
        string sqlPasswd = Constant.DB_PASSWORD;
        const string configFile = "config.xml";
        TableInfo info;
        List<string> tableColumnNames;
        List<string> tableColumnDisplayNames;
        Dictionary<string, DatabaseFieldNode> tableColumns;
        Dictionary<string, string> locationMap;
        string areaCode ="";
        const string areaColumnName = "sfdh";
        DateTime reportTimeBegin;
        DateTime reportTimeEnd;
        const string reportTimeColumnName = "bdsj";

        Dictionary<string, CrossQuery.FreeQuery> crossQueries;
        List<Button> crossQueryButtons;
        CrossQueryLoader crossQueryLoader = new CrossQueryLoader(); 
        public MainWindow()
        {
            InitializeComponent();
            PrepareTableInfo();
            dataSqlWrapper = new MySQLWrapper(sqlServer, dataSqlDatabase, sqlUser, sqlPasswd);
            mappingSqlWrapper = new MySQLWrapper(sqlServer, mappingSqlDatabase, sqlUser, sqlPasswd);
            
            CreateAreaComboBox();
            ReportTimeBeginDatePicker.SelectedDate = DateTime.Now;
            ReportTimeBeginDatePicker.DisplayDate = DateTime.Now; 
            ReportTimeEndDatePicker.SelectedDate = DateTime.Now;
            reportTimeBegin = DateTime.Now;
            reportTimeEnd = DateTime.Now;
            crossQueries = new Dictionary<string, CrossQuery.FreeQuery>();
            crossQueryButtons = new List<Button>();
            int i = 0;
            foreach (var queryName in crossQueryLoader.QueryNames)
            {
                CrossQuery.FreeQuery cq = crossQueryLoader.GetCrossQuery(queryName);
                crossQueries.Add(cq.DisplayName, cq);
                Button bn = new Button();
                bn.Content = cq.DisplayName;
                bn.SetValue(System.Windows.Controls.Grid.RowProperty, i / buttonsGrid.ColumnDefinitions.Count);
                bn.SetValue(System.Windows.Controls.Grid.ColumnProperty, i % buttonsGrid.ColumnDefinitions.Count);
                bn.SetValue(Control.HorizontalAlignmentProperty, HorizontalAlignment.Center);
                bn.SetValue(Control.VerticalAlignmentProperty, VerticalAlignment.Center);
                bn.SetValue(Control.HorizontalContentAlignmentProperty, HorizontalAlignment.Center);
                bn.SetValue(Control.VerticalContentAlignmentProperty, VerticalAlignment.Center);
                buttonsGrid.Children.Add(bn);
                bn.Click += crossQueryButtonClicked;
                crossQueryButtons.Add(bn);
                ++i;
            }



            CrossQueryWindow cqw = new CrossQueryWindow(dataSqlDatabase, "yuqing", new TableInfo());
            cqw.Show();
            
        }

        private void CreateAreaComboBox()
        {
            locationMap = GetReversedValueMapping(areaColumnName);
            foreach (var place in locationMap.Keys)
            {
                AreaComboBox.Items.Add(place);
            }
            if (locationMap.Count > 0)
            {
                AreaComboBox.SelectedIndex = 0;
            }
        }

        private void clearGridViewColumn(GridView gv)
        {
            gv.Columns.Clear();
        }

        private void appendGridViewColumn(GridView gv, string[] columnNames)
        {
            foreach(var name in columnNames){
                gv.Columns.Add(new GridViewColumn{
                    Header = name,
                    DisplayMemberBinding = new Binding(name)
                });
            }
        }

        private void crossQueryButtonClicked(object sender, RoutedEventArgs e)
        {
            Button bn = (Button)sender;
            CrossSearchWindow csw = new CrossSearchWindow(crossQueries[bn.Content.ToString()]);
            csw.Show();
        }

     
        private void AreaSearchButton_Click_1(object sender, RoutedEventArgs e)
        {
            if (!areaCode.Equals(""))
            {
                CaseDataListView.ItemsSource = null;
                string[] fields = tableColumnNames.ToArray<string>();
                string sql = "select * from yuqing where " + areaColumnName + "=" + areaCode;
                List<List<string>> data = SqlSearchData(sql, fields);
                string[] displayFields = tableColumnDisplayNames.ToArray<string>();
                UpdateData(data, displayFields);
            }
      
        }

        private void ReportTimeSearchButton_Click_1(object sender, RoutedEventArgs e)
        {
            CaseDataListView.ItemsSource = null;
            string begin = reportTimeBegin.ToString();
            string end = reportTimeEnd.ToString();
            string sql = string.Format("select * from yuqing where {0} >= '{1}' and {0} <= '{2}'", reportTimeColumnName, begin, end);
            string[] fields = tableColumnNames.ToArray<string>();
            List<List<string>> data = SqlSearchData(sql, fields);
            string[] displayFields = tableColumnDisplayNames.ToArray<string>();
            UpdateData(data, displayFields);
        }



        private List<List<string>> SqlSearchData(string sql, string[] fields)
        {
            return dataSqlWrapper.Select(sql, fields);
        }

        private List<List<string>> SqlSearchMapping(string sql, string[] fields)
        {
            return mappingSqlWrapper.Select(sql, fields);
        }

        private void UpdateData(List<List<string>> data, string[] displayFields){
            CaseDataListView.ItemsSource = data;
            for (int i = 0; i < displayFields.Length; ++i)
            {
                CaseDataGridView.Columns.Add(new GridViewColumn
                {
                    Header = displayFields[i],
                    DisplayMemberBinding = new Binding(string.Format("[{0}]", i))
                });
            }
        }

        private void PrepareTableInfo()
        {
            info = new TableInfo();
            tableColumns = info["yuqing"];
            tableColumnNames = new List<string>();
            tableColumnDisplayNames = new List<string>();
            foreach (var p in tableColumns)
            {
                tableColumnNames.Add(p.Key);
                tableColumnDisplayNames.Add(p.Value.DisplayName);
            }
        }

        private Dictionary<string, string> GetValueMapping(string columnName)
        {
            Dictionary<string, string> map = new Dictionary<string, string>();
            string sql = "select * from map_" + columnName;
            string[] fields = { "item", "code" };
            List<List<string>> rst = mappingSqlWrapper.Select(sql, fields);
            foreach (var pair in rst)
            {
                if (pair.Count == 2)
                {
                    map[pair[1]] = pair[0];
                }

            }
            return map;
        }

        private Dictionary<string, string> GetReversedValueMapping(string columnName)
        {
            Dictionary<string, string> map = new Dictionary<string, string>();
            string sql = "select * from map_" + columnName;
            string[] fields = { "item", "code" };
            List<List<string>> rst = mappingSqlWrapper.Select(sql, fields);
            foreach (var pair in rst)
            {
                if (pair.Count == 2)
                {
                    map[pair[0]] = pair[1];
                }

            }
            return map;
        }
        private void AreaComboBox_SelectionChanged_1(object sender, RoutedEventArgs e)
        {
            ComboBox cb = (ComboBox)sender;
            if(locationMap.Keys.Contains(cb.SelectedItem as string))
            {
                areaCode = locationMap[cb.SelectedItem as string];
            }
        }



        private void ReportTimeBeginDatePicker_SelectedDateChanged_1(object sender, SelectionChangedEventArgs e)
        {
            DatePicker dp = (DatePicker)sender;
            reportTimeBegin = (DateTime)dp.SelectedDate;
        }

        private void ReportTimeEndDatePicker_SelectedDateChanged_1(object sender, SelectionChangedEventArgs e)
        {
            DatePicker dp = (DatePicker)sender;
            reportTimeEnd = (DateTime)dp.SelectedDate;
        }
    }
}
